package com.woniuxy.controller;

import com.woniuxy.constants.ErrCodeConstants;
import com.woniuxy.dto.GridFileDto;
import com.woniuxy.entity.FileRecord;
import com.woniuxy.response.ResponseResult;
import com.woniuxy.response.ResponseUtil;
import com.woniuxy.service.FileService;
import com.woniuxy.service.GridFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileRecordController {
    @Autowired
    private FileService fileRecordService;
    @Autowired
    private GridFileService gridFileService;

    @PostMapping("/uploadOne")
    public ResponseResult<String> uploadFile(@RequestBody MultipartFile file) throws IOException {
        FileRecord fileRecordDoc = new FileRecord();
        fileRecordDoc.setFile(file);
        // TODO 设置创建人
        fileRecordService.save(fileRecordDoc);
        return ResponseUtil.success();
    }

    @PostMapping("/uploadList")
    public ResponseResult<String> uploadFiles(@RequestParam("files") MultipartFile[] files) throws IOException {
        log.info("{}", files.length);
        if (!ObjectUtils.isEmpty(files)) {
            List<FileRecord> recordFiles = new ArrayList<>();
            for (MultipartFile file : files) {
                FileRecord fileRecordDoc = new FileRecord();
                fileRecordDoc.setFile(file);
                recordFiles.add(fileRecordDoc);
            }
            fileRecordService.saveAll(recordFiles);
            return ResponseUtil.success();
        }
        return ResponseUtil.fail(ErrCodeConstants.DATA_CHECK,"上传文件为空");
    }

    @GetMapping("/downloadOne/{id}")
    public ResponseEntity<Resource> downloadOne(@PathVariable("id") String fileId) {
        FileRecord fileRecordDoc = fileRecordService.findById(fileId);
        if (!ObjectUtils.isEmpty(fileRecordDoc)) {
            Resource resource = new ByteArrayResource(fileRecordDoc.getFileContent());
            return ResponseEntity.ok().contentType(MediaType.parseMediaType(fileRecordDoc.getFileContentType()))
                    .body(resource);
        }
        return null;
    }

// ------------------------- 保存在文件桶中的大文件储存 -------------------------------

    @PostMapping("/uploadGridFile")
    public ResponseResult<String> uploadGridFile(@RequestBody MultipartFile file) throws IOException {
        Map<String, String> mata = new HashMap<>();
        mata.put("test", "testMata");
        GridFileDto fileDto = new GridFileDto();
        fileDto.setFileContent(file.getBytes());
        fileDto.setFileContentType(file.getContentType());
        fileDto.setFileName(file.getOriginalFilename());
        fileDto.setMetadata(mata);
        gridFileService.save(fileDto);
        return ResponseUtil.success();
    }

    @PostMapping("/uploadGridFiles")
    public ResponseResult<String> uploadGridFiles(@RequestParam("files") MultipartFile[] files) throws IOException {
        Map<String, String> mata = new HashMap<>();
        mata.put("test", "testMata");
        List<GridFileDto> fileDtos = new ArrayList<>();
        for (MultipartFile file : files) {
            GridFileDto fileDto = new GridFileDto();
            fileDto.setFileContent(file.getBytes());
            fileDto.setFileContentType(file.getContentType());
            fileDto.setFileName(file.getOriginalFilename());
            fileDto.setMetadata(mata);
            fileDtos.add(fileDto);
        }
        gridFileService.saveAll(fileDtos);
        return ResponseUtil.success();

    }


    @GetMapping({ "/downloadGrid/{id}" })
    public ResponseEntity<Resource> download(@PathVariable("id") String id) throws Exception {
        GridFileDto dto = this.gridFileService.get(id);
        Resource resource = new ByteArrayResource(dto.getFileContent());
        String contentType = dto.getFileContentType();
        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).body((resource));
    }

}
